package org.sample.commons.net;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.Map;
import java.util.Set;

public class NetUtils {

    /**
     * 获取本机IP地址
     */
    public static InetAddress getLocalHostLANAddress() {
        try {
            InetAddress candidateAddress = null;
            // 遍历所有的网络接口
            for (Enumeration networkInterfaces = NetworkInterface.getNetworkInterfaces(); networkInterfaces.hasMoreElements(); ) {
                NetworkInterface networkInterface = (NetworkInterface) networkInterfaces.nextElement();
                // 在所有的接口下再遍历IP
                for (Enumeration inetAddresses = networkInterface.getInetAddresses(); inetAddresses.hasMoreElements(); ) {
                    InetAddress inetAddress = (InetAddress) inetAddresses.nextElement();
                    if (!inetAddress.isLoopbackAddress()) {// 排除loopback类型地址
                        if (inetAddress.isSiteLocalAddress()) {
                            // 如果是site-local地址，就是它了
                            return inetAddress;
                        } else if (candidateAddress == null) {
                            // site-local类型的地址未被发现，先记录候选地址
                            candidateAddress = inetAddress;
                        }
                    }
                }
            }
            if (candidateAddress != null) {
                return candidateAddress;
            }
            // 如果没有发现 non-loopback地址.只能用最次选的方案
            return InetAddress.getLocalHost();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String buildUrl(String url, Map params) {
        StringBuilder result = new StringBuilder(url.length() + params.size() * 10);
        result.append(url);
        if (url.contains("?"))
            result.append("&");
        else
            result.append("?");
        Set<Map.Entry> entrySet = params.entrySet();
        for (Map.Entry entry : entrySet) {
            Object value = entry.getValue();
            if (value != null)
                result.append(entry.getKey()).append("=").append(value).append("&");
        }
        result.deleteCharAt(result.length() - 1);
        return result.toString();
    }

    public static String buildUrl(String url, String... params) {
        StringBuilder result = new StringBuilder(url.length() + params.length * 10);
        result.append(url);
        if (url.contains("?"))
            result.append("&");
        else
            result.append("?");
        for (int i = 0; i < params.length; i += 2) {
            String name = params[i];
            String value = params[i + 1];
            result.append(name).append("=").append(value).append("&");
        }
        result.deleteCharAt(result.length() - 1);
        return result.toString();
    }
}